import json
from bazy.models import *
from django.http import HttpResponse
import hashlib
from bazy.login import Login
from bazy.forms import *
from django.db import IntegrityError
import base64
import time


def create(request):
	
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	form = CreateHooliganForm(request.POST, request.FILES)
	if not form.is_valid():
		return HttpResponse(json.dumps([{'Error':-2}]))
	if not( request.FILES['photo'].name.lower().endswith('.png') or request.FILES['photo'].name.lower().endswith('.jpg')):
		 return HttpResponse(json.dumps([{'Error':-3}]))
	hool = Hooligan(user=User.objects.get(pk=request.POST['user']) , name=request.POST['name'],lastname=request.POST['lastname'],date=time.strftime('%Y-%m-%d %H:%M:%S') )
	hool.save()
	hool.photoUrl= handleUploadedFile(request.FILES['photo'])
	hool.save()
	return HttpResponse(json.dumps([{'Error':0}]))

def createb64(request):
	
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method!='POST':
		return HttpResponse(json.dumps([{'Error':-2}]))
	hool = Hooligan(user=User.objects.get(pk=request.POST['user']) , name=request.POST['name'],lastname=request.POST['lastname'],date=time.strftime('%Y-%m-%d %H:%M:%S') )
	hool.save()
	hool.photoUrl= handleb64File(request.POST['photo'])
	hool.save()
	return HttpResponse(json.dumps([{'Error':0}]))

def handleUploadedFile(f):
	
	millis = int(round(time.time() * 1000))
	name=str(millis)+f.name.encode('ascii','ignore');
	name = hashlib.sha1(name).hexdigest() 
	with open('imgs/'+name+str(millis)+f.name[-4:], 'wb+') as destination:
		for chunk in f.chunks():
			destination.write(chunk)
	return ''+name+str(millis)+f.name[-4:]

def handleb64File(f):
	millis = int(round(time.time() * 1000))
	name=str(millis)
	name = hashlib.sha1(name).hexdigest() 
	with open('imgs/'+name+str(millis)+'.png', 'wb+') as destination:
		destination.write(base64.decodestring(f))
	return ''+name+str(millis)+'.png'

def getAll(request):
	
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	hoolsArray = Hooligan.objects.all()
	jsonList = list()
	for hooligan in hoolsArray:
		jsonList.append({'id':hooligan.id,
						 'name':hooligan.name,
						 'lastname':hooligan.lastname,
						 'photoUrl':hooligan.photoUrl,
						 'date':hooligan.date.strftime('%Y-%m-%d %H:%M:%S'),
						 'user':hooligan.user.username,
						 'userId':hooligan.user.id })
#   print json.dumps(jsonList)
	return HttpResponse(json.dumps(jsonList))


def getImage(request,from_url):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	image_data = open('imgs/'+from_url, 'rb').read()
	return HttpResponse(image_data, mimetype="image/png")

def get(request):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method=='POST':
		id = request.POST.get('id',-1)
	else:
		return HttpResponse(json.dumps([{'Error':-2}]))
	if(id<=0):
		return HttpResponse(json.dumps([{'Error':-2}]))
	hooligan= Hooligan.objects.get(pk=id)
	return HttpResponse(json.dumps([{'id':hooligan.id,
						 'name':hooligan.name,
						 'lastname':hooligan.lastname,
						 'photoUrl':hooligan.photoUrl,
						 'date':hooligan.date.strftime('%Y-%m-%dT%H:%M:%S'),
						 'user':hooligan.user.username,
						 'userId':hooligan.user.id }]))
def getByEventId(request):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method=='POST':
		id = request.POST.get('id',-1)
	else:
		return HttpResponse(json.dumps([{'Error':-2}]))
	if(id<=0):
		return HttpResponse(json.dumps([{'Error':-2}]))
	hoolsArray = Hooligan.objects.filter(event__pk=int(request.POST.get('id',1)))
	jsonList = list()
	for hooligan in hoolsArray:
		jsonList.append({'id':hooligan.id,
						 'name':hooligan.name,
						 'lastname':hooligan.lastname,
						 'photoUrl':hooligan.photoUrl,
						 'date':hooligan.date.strftime('%Y-%m-%d %H:%M:%S'),
						 'user':hooligan.user.username,
						 'userId':hooligan.user.id })
#   print json.dumps(jsonList)
	return HttpResponse(json.dumps(jsonList))
def edit(request):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method!='POST':
		return HttpResponse(json.dumps([{'Error':-2}]))
	if request.POST.get('set_photo',0)==1:
		if not( request.FILES['photo'].name.lower().endswith('.png') or request.FILES['photo'].name.lower().endswith('.jpg')):
			return HttpResponse(json.dumps([{'Error':-3}]))
	hool = Hooligan.objects.get(pk=request.POST['id'])
	hool.name=name=request.POST['name']
	hool.lastname=request.POST['lastname']
	
	if request.POST.get('set_photo',0)=='1':
		print request.FILES['photo'].name
		hool.photoUrl= handleUploadedFile(request.FILES['photo'])
	hool.save()
	return HttpResponse(json.dumps([{'Error':0}]))

def delete(request):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method!='POST':
		return HttpResponse(json.dumps([{'Error':-2}]))
		
	Hooligan.objects.get(pk=request.POST['id']).delete()
	return HttpResponse(json.dumps([{'Error':0}]))

def addHooliganToEvent(request):
	log = Login(request)
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method != 'POST':
		return HttpResponse(json.dumps([{'Error':-2}]))
	form = AddEventToHooligan(request.POST)
	if form.is_valid() is not True:
		return HttpResponse(json.dumps([{'Error':-2}]))
	event= Event.objects.get(pk=request.POST.get('event_id',0))
	hooligan=Hooligan.objects.get(pk=request.POST.get('hooligan_id',0))
	event.hooligans.add(hooligan)
	event.save()
	return HttpResponse(json.dumps([{'Error':-0}]))